using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.ERPModels.WarehouseManagement;
using ERP.WarehouseManagement.Dto;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace ERP.WarehouseManagement
{
    /// <summary>
    /// 库存交易服务实现
    /// </summary>
    public class InventoryTransactionService : ApplicationService, IInventoryTransactionService
    {
        private readonly IRepository<InventoryTransaction, int> _inventoryTransactionRepository;
        
        public InventoryTransactionService(
            IRepository<InventoryTransaction, int> inventoryTransactionRepository)
        {
            _inventoryTransactionRepository = inventoryTransactionRepository;
        }

        /// <summary>
        /// 获取库存交易统计数据
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns>库存交易统计结果</returns>
        public async Task<InventoryTransactionStatisticsResult> GetInventoryTransactionStatisticsAsync(InventoryTransactionQueryDto queryDto)
        {
            // 确定查询月份，如果未指定则使用当前月份
            var queryMonth = queryDto.QueryMonth ?? DateTime.Now;
            var startDate = new DateTime(queryMonth.Year, queryMonth.Month, 1);
            var endDate = startDate.AddMonths(1).AddDays(-1);

            // 构建基本查询
            var query = await _inventoryTransactionRepository.WithDetailsAsync();
            var filteredQuery = query.Where(t => t.TransactionDate >= startDate && t.TransactionDate <= endDate);

            // 应用筛选条件
            if (queryDto.WarehouseId.HasValue)
            {
                filteredQuery = filteredQuery.Where(t => t.WarehouseId == queryDto.WarehouseId.Value);
            }

            if (queryDto.MaterialClassId.HasValue)
            {
                filteredQuery = filteredQuery.Where(t => t.MaterialClassId == queryDto.MaterialClassId.Value);
            }

            if (!string.IsNullOrWhiteSpace(queryDto.MaterialKeyword))
            {
                filteredQuery = filteredQuery.Where(t => 
                    t.MaterialCode.Contains(queryDto.MaterialKeyword) || 
                    t.MaterialName.Contains(queryDto.MaterialKeyword));
            }

            // 获取查询结果
            var transactions = filteredQuery.ToList();

            // 按日期分组统计
            var dailyStats = transactions
                .GroupBy(t => t.TransactionDate.Date)
                .Select(g => new
                {
                    Date = g.Key,
                    InboundQuantity = g.Where(t => t.TransactionType == 1).Sum(t => t.Quantity),
                    OutboundQuantity = g.Where(t => t.TransactionType == 2).Sum(t => t.Quantity)
                })
                .OrderBy(s => s.Date)
                .ToList();

            // 确保每天都有数据（即使无交易记录也显示零）
            var result = new InventoryTransactionStatisticsResult();
            for (var date = startDate; date <= endDate; date = date.AddDays(1))
            {
                var stats = dailyStats.FirstOrDefault(s => s.Date == date.Date);
                result.DailyStatistics.Add(new InventoryTransactionStatisticsDto
                {
                    Date = date.ToString("yyyy-MM-dd"),
                    InboundQuantity = stats?.InboundQuantity ?? 0,
                    OutboundQuantity = stats?.OutboundQuantity ?? 0
                });
            }

            return result;
        }
    }
} 